package com.xinzhi.service.impl;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.xinzhi.domain.AliPay;
import com.xinzhi.domain.Man;
import com.xinzhi.mapper.*;
import com.xinzhi.service.LoginService;
import com.xinzhi.service.OrderService;
import com.xinzhi.service.UserService;
import com.xinzhi.utils.RedisUtil;
import com.xinzhi.domain.entity.*;
import com.xinzhi.domain.Applicant;
import com.xinzhi.domain.vo.OrderDetailsListVO;
import com.xinzhi.domain.vo.OrderListVO;
import com.xinzhi.domain.entity.need.OrderRequest;
import com.xinzhi.domain.Product;
import com.xinzhi.utils.Result;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


@EnableScheduling
@Service
public class OrderServiceimpl implements OrderService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    UserService userService;

    @Resource
    private ApplicantMapper applicantMapper;

    @Resource
    private ManMapper manMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private CartMapper cartMapper;
    @Resource
    private LoginService loginService;




    /**
     * 生成订单以及订单详情
     * @param list
     * @return
     */

    @Transactional
    @Override
    public Result newOrder(List<OrderRequest> list, HttpServletRequest request) {
        Orders order = new Orders();
        //---------------------------
        Random a= new Random();
        String water = IdUtil.getSnowflake(1, 20).nextId()+"";
        String now = DateUtil.now();//生成订单时间
        int sum  = 0;
        String msg  = "";
        BigDecimal allPrice = new BigDecimal("0");  // 总价
        for (OrderRequest orderRequest : list) {
            Orders_detail orders_detail = new Orders_detail();
            //--------------------------------------
            Integer userId = orderRequest.getUserId();
            Integer productId = orderRequest.getProductId();
//            System.out.println(orderRequest.getNum());
            Integer num = orderRequest.getNum();
            Product product = productMapper.selectPriceByGoodsId(productId);
            if (product.getStock() < orderRequest.getNum())
            {
                return  Result.error(200,product.getProductName()+"已售罄");
            }
            //生成订单详情并且移除购物车
            cartMapper.delProduct(loginService.checkToken(request.getHeader("token")).getUserId(),productId);
            sum = sum+num;
            msg = msg+(sum+"件"+product.getProductName()+"   ");
            //--------------订单详情表------------------
            orders_detail.setNumber(num);
            orders_detail.setOrdersId(water);
            orders_detail.setProductId(productId);
            //自提人信息和自提点
            order.setManId(orderRequest.getManId());//接收到传过来的自提人id，存到订单表-7
            order.setPlaceId(orderRequest.getPlaceId());//接收到传来的自提点id，存到订单表-8
            //-----------------------数量单价x数量 得到总价----------
            // 从参数接收到的数量，转型成Big
            BigDecimal number=BigDecimal.valueOf((orderRequest.getNum()));
            BigDecimal multiply = product.getPrice().multiply(number);
            //用BigDecimal的乘法方式计算总价
            orders_detail.setTotal(multiply);
            orderMapper.newDetails(orders_detail);
            allPrice = allPrice.add(multiply);
            order.setUserId(userId);//用户id-6
            //提货人+提货点
        }
        order.setOrderNum(water);//本次订单号-1
        order.setOrderTime(now);//本次订单生成时间-2
        order.setId(0);//订单状态-3
        order.setNum(sum);//商品总数量-5
        order.setTotal(allPrice);//订单总价---4
        order.setUserId(loginService.checkToken(request.getHeader("token")).getUserId());
        System.out.println(order);
        orderMapper.generate(order);

        msg = msg +("下单成功");
        //将当前订单放到redis中设置失效时间
        redisUtil.hset("order",water,0,1200);
        System.out.println(redisUtil.hget("order",water));
        //支付宝内容
        AliPay aliPay = new AliPay();
        aliPay.setTotalAmount(allPrice.doubleValue());
        aliPay.setTraceNo(water);
        aliPay.setSubject("美团优选订单支付");
        return Result.ok(aliPay);
    }

    /**
     * 订单中心-查看订单
     * @param userId
     * @param state
     * @return
     */
    @Override
    @Transactional
    public Result seeOrdersByState(Integer userId, Integer state, Integer nowPage) {
        if (nowPage == null) nowPage = 1;
        List<OrderListVO> orderListVOS = new ArrayList<>();
        Integer allpage = 0;
        List<Orders> orders = orderMapper.getOrder(userId,null, state);

        for (Orders order : orders) {
            allpage = (orders.size()%2) ==  0  ? orderListVOS.size()/2 : orderListVOS.size()/2 +1;
            List<Orders_detail> details = orderMapper.getDetails(order.getOrderNum());
            List<OrderDetailsListVO> orderDetailsListVOS = new ArrayList<>();
            //便利拿到商品id，建一个VO的子集合，轮流set
            for (Orders_detail detail : details) {
                OrderDetailsListVO orderDetailsListVO = new OrderDetailsListVO();
                orderDetailsListVO.setNumber(detail.getNumber());
                orderDetailsListVO.setOrdersId(detail.getOrdersId());
                orderDetailsListVO.setTotal(detail.getTotal());
                //details拿到id  再查商品信息  并且减少库存
                com.xinzhi.domain.Product product = productMapper.selectPriceByGoodsId(detail.getProductId());
                orderDetailsListVO.setProductName(product.getProductName());
                orderDetailsListVO.setMainImg(product.getMainImg());
                orderDetailsListVO.setPrice(product.getPrice());
                orderDetailsListVOS.add(orderDetailsListVO);
            }
            OrderListVO orderListVO = new OrderListVO();
            orderListVO.setSonOrder(orderDetailsListVOS);
            orderListVO.setOrderNum(order.getOrderNum());
            orderListVO.setOrderTime(order.getOrderTime());
            orderListVO.setTotal(order.getTotal());
            orderListVO.setNum(order.getNum());
            Applicant place = applicantMapper.getById(order.getPlaceId());
            if (place == null){
                return Result.error("系统错误，订单中自提点被取消");
            }
            com.xinzhi.domain.Man manInfo = manMapper.getManInfo(order.getManId());
            orderListVO.setApplicantAddress(place.getApplicantAddress());
            orderListVO.setApplicantRegion(place.getApplicantRegion());
            orderListVO.setStore(place.getStore());
            orderListVO.setManName(manInfo.getName());
            orderListVO.setPhone(manInfo.getPhone());
            orderListVO.setAllpage(allpage);
            orderListVOS.add(orderListVO);
        }

        if (allpage < nowPage){
            nowPage = allpage;
        }
        List<OrderListVO> page = ListUtil.page(nowPage-1, 6, orderListVOS);

        return Result.ok(page);
    }

    /**
     * 付款成功/取货成功
     * @param orderNum
     * @param state
     * @return
     */
    @Override
    public Result updateOrderState(String orderNum, Integer state) {
        int i = orderMapper.updateOrderState(orderNum, state);
        if(state == 1){
            if (i<0){
                return Result.error(250,"付款失败，请求超时");
            }
            return Result.ok("付款成功");
        }
        if(state == 2){
            if (i<0){
                return Result.error(200,"扫码取货失败，请重新确认");
            }
            return Result.ok("取货成功");
        }
        return Result.error(999,"后台异常");
    }

    /**
     * 定时过期20分钟未支付订单
     * @return
     */
    @Override
    @Scheduled(fixedRate = 30*1000)
    public String crossTime() {
        //查到所有的订单号为0的订单，开启定时任务
        List<Orders> orderByTypeO = orderMapper.getOrderByTypeO();
//        //遍历集合
        for (Orders orders : orderByTypeO) {
            Object order = redisUtil.hget("order", orders.getOrderNum());
            if (order == null && orders.getState()==0){
                orderMapper.updateOrderState(orders.getOrderNum(),9);
             //然后对应订单详情信息  拿到商品id和数量   库存加回去
                List<Orders_detail> details = orderMapper.getDetails(orders.getOrderNum());
                for (Orders_detail detail : details) {
                    com.xinzhi.domain.Product product = productMapper.selectPriceByGoodsId(detail.getProductId());
                    productMapper.updateKucun(product.getStock(),product.getId());
                }
            }
        }

        return "";
    }

    /**
     * 展示所有的自提点
     * @param
     * @return
     */
    @Override
    public List<Applicant> showPoint() {
        List<Applicant> applicants = applicantMapper.showPoint();
        return  applicants;
    }

    /**
     * 看自提人信息
     * @return
     */
    @Override
    public Result showManById(Integer userId) {
        if (userId == null){
            return Result.error(500,"非法id");
        }
        List<Man> men = manMapper.showManInfo(userId);
        if (men.size() ==0){
            return Result.ok("请添加自提人信息"); }
        return Result.ok(men);
    }
    /**
     * 关于团长的订单
     * @param applicantId
     * @param state
     * @param nowPage
     * @return
     */
    @Override
    public List<OrderListVO> underOrdersInfo(Integer applicantId, Integer state, Integer nowPage) {
        List<OrderListVO> orderListVOS = new ArrayList<>();
        Integer allpage = 0;
        List<Orders> orders = orderMapper.getOrder(null,applicantId, state);

        for (Orders order : orders) {
            allpage = (orderListVOS.size()%5) ==  0  ? orderListVOS.size()/5 : orderListVOS.size()/2 +1;
            List<Orders_detail> details = orderMapper.getDetails(order.getOrderNum());
            List<OrderDetailsListVO> orderDetailsListVOS = new ArrayList<>();
            //便利拿到商品id，建一个VO的子集合，轮流set
            for (Orders_detail detail : details) {
                OrderDetailsListVO orderDetailsListVO = new OrderDetailsListVO();
                orderDetailsListVO.setNumber(detail.getNumber());
                orderDetailsListVO.setOrdersId(detail.getOrdersId());
                orderDetailsListVO.setTotal(detail.getTotal());
                //details拿到id  再查商品信息  并且减少库存
                com.xinzhi.domain.Product product = productMapper.selectPriceByGoodsId(detail.getProductId());
                orderDetailsListVO.setProductName(product.getProductName());
                orderDetailsListVO.setMainImg(product.getMainImg());
                orderDetailsListVO.setPrice(product.getPrice());
                orderDetailsListVOS.add(orderDetailsListVO);
            }
            OrderListVO orderListVO = new OrderListVO();
            orderListVO.setSonOrder(orderDetailsListVOS);
            orderListVO.setOrderNum(order.getOrderNum());
            orderListVO.setOrderTime(order.getOrderTime());
            orderListVO.setTotal(order.getTotal());
            orderListVO.setNum(order.getNum());
            Applicant place = applicantMapper.getById(order.getPlaceId());
            Man manInfo = manMapper.getManInfo(order.getManId());
            orderListVO.setApplicantAddress(place.getApplicantAddress());
            orderListVO.setApplicantRegion(place.getApplicantRegion());
            orderListVO.setStore(place.getStore());
            orderListVO.setManName(manInfo.getName());
            orderListVO.setPhone(manInfo.getPhone());
            orderListVO.setAllpage(allpage);
            orderListVOS.add(orderListVO);
        }
        if (allpage < nowPage){
            nowPage = allpage;
        }
        List<OrderListVO> page = ListUtil.page(nowPage-1, 5, orderListVOS);
        return page;
    }

    /**
     * 接收到购物车的内容，返回一个详情信息
     * @param userId
     * @return
     */
    @Override
    public OrderListVO goBuy(Integer userId,Integer productId) {
        //给一个默认的提货人和提货点

        OrderListVO orderListVO = new OrderListVO();
        List<Man> men = manMapper.showManInfo(userId);
        List<Applicant> applicants = applicantMapper.showPoint();
        if (men==null){
            orderListVO.setManName("请添加自提人信息");
            orderListVO.setPhone("请添加自提人手机号");

        }
        orderListVO.setManName(men.get(0).getName());
        orderListVO.setPhone(men.get(0).getPhone());
        orderListVO.setStore(applicants.get(0).getStore());
        //======================================================
        // wzk 修改 1028/19：11 原代码  if (productId != null)
        // 没有接收到 productId 参数
        // System.out.println(productId);
        //======================================================
        if (productId != null && productId != 0){
            System.out.println("=================================");
            List<OrderDetailsListVO> nowBuy = new ArrayList<>();
            OrderDetailsListVO now = new OrderDetailsListVO();
            com.xinzhi.domain.Product product = productMapper.selectPriceByGoodsId(productId);
            now.setMainImg(product.getMainImg());
            now.setNumber(1);
            now.setPrice(product.getPrice());
            now.setProductName(product.getProductName());
            now.setTotal(product.getPrice());
            nowBuy.add(now);
            orderListVO.setTotal(product.getPrice());
            orderListVO.setSonOrder(nowBuy);
            return orderListVO;
        }
        List<Cart> cartInfo = orderMapper.getCartInfo(userId);
        List<OrderDetailsListVO> orderDetailsListVOS = new ArrayList<>();
        BigDecimal allPrice = new BigDecimal("0");  // 总价
        for (Cart cart : cartInfo) {
            OrderDetailsListVO orderDetailsListVO = new OrderDetailsListVO();
            com.xinzhi.domain.Product product = productMapper.selectPriceByGoodsId(cart.getProductId());
            orderDetailsListVO.setMainImg(product.getMainImg());
            orderDetailsListVO.setPrice(product.getPrice());
            BigDecimal number=BigDecimal.valueOf((cart.getNum()));
            BigDecimal multiply = product.getPrice().multiply(number);
            orderDetailsListVO.setTotal(multiply);
            orderDetailsListVO.setNumber(cart.getNum());
            orderDetailsListVO.setProductId(cart.getProductId());
            orderDetailsListVO.setProductName(product.getProductName());
            allPrice = allPrice.add(multiply);
            System.out.println(allPrice);
            orderListVO.setTotal(allPrice);
            orderDetailsListVOS.add(orderDetailsListVO);
            orderListVO.setSonOrder(orderDetailsListVOS);
        }
        return  orderListVO;
    }

    @Override
    public Result pay(String orderNum) {
        Orders order = orderMapper.getOrdersByOrderNum(orderNum);
        System.out.println("调用本地支付接口");

        return Result.ok("正在前往对订单号为"+order.getOrderNum()+"的支付页面,总价为："+order.getTotal());
    }


}


